import { socket } from "../config/websocket/socket";
import service from "../utils/request";

/**
 * WebSocket管理器
 * 管理WebSocket连接、消息发送和事件处理
 */
export class WebSocketManager {
  constructor(context) {
    this.context = context; // Vue组件实例
    this.eventListeners = new Map();
    this.isInitialized = false;
  }

  /**
   * 初始化WebSocket管理器
   */
  init() {
    if (this.isInitialized) {
      return;
    }

    this.setupEventListeners();
    socket.init();
    this.isInitialized = true;
  }

  /**
   * 设置事件监听器
   */
  setupEventListeners() {
    // Socket状态监听
    this.addEventListener("socketStatus", this.handleSocketStatus.bind(this));
    
    // 好友关系初始化监听
    this.addEventListener("initFriendshipId", this.handleInitFriendshipId.bind(this));
    
    // 容器初始化监听
    this.addEventListener("initContainer", this.handleInitContainer.bind(this));
    
    // 视频通话响应监听
    this.addEventListener("videoCallsResponse", this.handleVideoCallsResponse.bind(this));
    
    // 语音通话响应监听
    this.addEventListener("voiceCallsResponse", this.handleVoiceCallsResponse.bind(this));
  }

  /**
   * 添加事件监听器
   */
  addEventListener(eventName, handler) {
    window.addEventListener(eventName, handler);
    this.eventListeners.set(eventName, handler);
  }

  /**
   * 移除所有事件监听器
   */
  removeAllEventListeners() {
    this.eventListeners.forEach((handler, eventName) => {
      window.removeEventListener(eventName, handler);
    });
    this.eventListeners.clear();
  }

  /**
   * 处理Socket状态变化
   */
  handleSocketStatus(res) {
    const status = res.detail.data;
    const isOnline = status === 1;

    // 更新本地状态
    this.context.isOnline = isOnline;

    // 更新全局状态
    this.context.$store.dispatch("chat/setOnlineStatus", isOnline);
  }

  /**
   * 处理好友关系初始化
   */
  handleInitFriendshipId() {
    this.context.initFriendshipId();
  }

  /**
   * 处理容器初始化
   */
  handleInitContainer() {
    this.context.initContainer();
  }

  /**
   * 处理视频通话响应
   */
  handleVideoCallsResponse(event) {
    if (this.context.select === 1) {
      this.context.dialogVisibleVideo = true;
      this.context.$nextTick(() => {
        this.context.safeRefCall('videoCalls', 'VCResponse', event.detail.data);
      });
    }
  }

  /**
   * 处理语音通话响应
   */
  handleVoiceCallsResponse(event) {
    if (this.context.select === 1) {
      this.context.dialogVisibleVoice = true;
      this.context.$nextTick(() => {
        this.context.safeRefCall('voiceCalls', 'voiceResponse', event.detail.data);
      });
    }
  }

  /**
   * 发送WebSocket消息
   */
  sendMessage(message) {
    if (socket && socket.send) {
      socket.send(message);
    } else {
      console.error('WebSocket连接未建立');
    }
  }

  /**
   * 发起视频通话
   */
  async initiateVideoCall(friendshipId) {
    try {
      const loading = this.context.$loading({
        lock: true,
        text: "建立通信中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      setTimeout(async () => {
        loading.close();
        
        try {
          const res = await service({
            method: "get",
            url: "users/userInfo/userOnlineStatus",
            params: {
              userInfo: friendshipId,
            },
          });

          if (res && res.code === 200) {
            if (res.data === true) {
              this.context.sendMessage.action = 10007;
              this.context.sendMessage.receiverId = friendshipId;
              this.sendMessage(this.context.sendMessage);
              
              this.context.dialogVisibleVideo = true;
              this.context.videoCountdownTimer = setTimeout(() => {
                this.context.safeRefCall('videoCalls', 'closeVideo', this.context.sendMessage.receiverId);
              }, 10 * 1000);
            } else {
              this.context.$notify({
                title: "视频通话",
                type: "warning",
                message: "对方不在线，无法进行视频通话",
              });
            }
          }
        } catch (error) {
          console.error('检查在线状态失败:', error);
          this.context.$notify({
            title: "视频通话",
            type: "error",
            message: "网络错误，请稍后重试",
          });
        }
      }, 2000);
    } catch (error) {
      console.error('发起视频通话失败:', error);
    }
  }

  /**
   * 发起语音通话
   */
  async initiateVoiceCall(friendshipId) {
    try {
      const loading = this.context.$loading({
        lock: true,
        text: "建立通信中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      setTimeout(async () => {
        loading.close();
        
        try {
          const res = await service({
            method: "get",
            url: "users/userInfo/userOnlineStatus",
            params: {
              userInfo: friendshipId,
            },
          });

          if (res && res.code === 200) {
            if (res.data === true) {
              this.context.sendMessage.action = 10008;
              this.context.sendMessage.receiverId = friendshipId;
              this.sendMessage(this.context.sendMessage);
              
              this.context.dialogVisibleVoice = true;
              this.context.voiceCountdownTimer = setTimeout(() => {
                this.context.safeRefCall('voiceCalls', 'closeVoice', this.context.sendMessage.receiverId);
              }, 10 * 1000);
            } else {
              this.context.$notify({
                title: "语音通话",
                type: "warning",
                message: "对方不在线，无法进行语音通话",
              });
            }
          }
        } catch (error) {
          console.error('检查在线状态失败:', error);
          this.context.$notify({
            title: "语音通话",
            type: "error",
            message: "网络错误，请稍后重试",
          });
        }
      }, 2000);
    } catch (error) {
      console.error('发起语音通话失败:', error);
    }
  }

  /**
   * 通知好友上线
   */
  async notifyFriendOnline(friendId) {
    try {
      const params = {
        friendId: friendId,
        content: "",
      };
      
      const res = await service.post("users/notify/friend/online", params);
      
      if (res.code === 200) {
        this.context.$notify({
          type: "success",
          title: "邀请好友上线",
          message: "发送成功",
        });
      } else {
        this.context.$notify({
          type: "error",
          title: "邀请好友上线",
          message: res.message,
        });
      }
    } catch (error) {
      console.error('通知好友上线失败:', error);
      this.context.$notify({
        type: "error",
        title: "邀请好友上线",
        message: "网络错误，请稍后重试",
      });
    }
  }

  /**
   * 处理Socket命令
   */
  handleSocketCommand(command) {
    switch (command) {
      case "online":
        socket.init();
        break;
      case "offline":
        if (socket.websock !== null) {
          this.context.$confirm("离线后将无法实时接收到任何信息?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              socket.close();
            })
            .catch(() => {});
        }
        break;
    }
  }

  /**
   * 销毁WebSocket管理器
   */
  destroy() {
    // 移除所有事件监听器
    this.removeAllEventListeners();
    
    // 清理 WebSocket 连接
    if (socket && socket.close) {
      socket.close();
    }
    
    this.isInitialized = false;
    this.context = null;
  }
}

export default WebSocketManager;
